package com.zh.webflux.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * 包装响应Response的数据
 *
 * @author ZH
 * @date 16:20 2020/12/29
 */
@Slf4j
public final class ResponseDataWrapper {
    private static final String regex = "(\"password\"[\\s]*:[\\s]*\")(.*?)(\")";


    /**
     * 将对象转为json数据，并包装为ByteBuffer返回
     *
     * @param object
     * @return
     */
    public static ByteBuffer wrapper(Object object) {
        String jsonData = "";
        try {
            jsonData = new ObjectMapper()
                    .writeValueAsString(object)
                    .replaceAll(regex, "$1$3");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.error("object转换json错误 msg: {}", e.getMessage());
        }
        log.debug("jsonData = " + jsonData);

        return Unpooled.copiedBuffer(jsonData, StandardCharsets.UTF_8).nioBuffer();
    }

}
